package com.anysoft.web;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.anysoft.R;
import com.anysoft.WebViewNetworkProtocol;
import com.anysoft.base.BaseActivity;
import com.anysoft.event.TimeOutEvent;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.StringUtils;
import com.anysoft.view.HProgressBarLoading;
import com.anysoft.view.dialog.IcbcDialog;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ren.yale.android.cachewebviewlib.CacheWebView;

import static com.anysoft.HostConstant.HOST_WEB_URL_HEADER_GYZT;
import static com.anysoft.MentorConst.APP_CACAHE_DIRNAME;

/**
 * Created by wwq on 2017/4/8.
 * 目前废弃 在线专家
 */

public class WisdomActivity extends BaseActivity {


    @BindView(R.id.wv)
    CacheWebView mWebView;
    @BindView(R.id.tv_item_web_error)
    TextView tvItemWebError;
    @BindView(R.id.ll_item_web_error)
    LinearLayout llItemWebError;
    @BindView(R.id.top_progress)
    HProgressBarLoading top_progress;

    public String loadUrl;
    public Intent mIntent = new Intent();
    private boolean isLoadError = false;
    private boolean isCanPressBack = true;

    private String loginAfterUrl = null;
    private boolean isCloaseOnBackKey = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_webview_wisdom);
        ButterKnife.bind(this);

        initUrl(HttpUtils.getCommonParams2StringByWeb(mActivity)
                + "&shareClass=A&cusNo=" + getFundCustomerNo());
        if (CommonUtil.isNetWorkConnected(mActivity)) {
            initView(loadUrl);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private boolean isFinishGo;

    public void initView(String url) {
//        StatService.onPageStart(mActivity,"recommendScheme.html");
        isFinishGo = false;

        mWebView.getSettings().setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= 21) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);  //设置 缓存模式
        // 开启 DOM storage API 功能
        mWebView.getSettings().setDomStorageEnabled(true);
        //开启 database storage API 功能
        mWebView.getSettings().setDatabaseEnabled(true);
        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
        MentorLogger.Log(TAG, "cacheDirPath=" + cacheDirPath);
        //设置数据库缓存路径
        mWebView.getSettings().setDatabasePath(cacheDirPath);
        //设置  Application Caches 缓存目录
        mWebView.getSettings().setAppCachePath(cacheDirPath);
        //开启 Application Caches 功能
        mWebView.getSettings().setAppCacheEnabled(true);

//        //TODO 关闭万恶的缓存，效果未知
//        mWebView.getSettings().setJavaScriptEnabled(true);
//        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);  //关闭webview中缓存
//        // 开启 DOM storage API 功能
//        mWebView.getSettings().setDomStorageEnabled(false);
//        //开启 database storage API 功能
//        mWebView.getSettings().setDatabaseEnabled(false);
//        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
//        MentorLogger.Log(TAG, "cacheDirPath=" + cacheDirPath);
//        //设置数据库缓存路径
//        mWebView.getSettings().setDatabasePath(cacheDirPath);
//        //设置  Application Caches 缓存目录
//        mWebView.getSettings().setAppCachePath(cacheDirPath);
//        //开启 Application Caches 功能 false--关闭，即，H5的缓存无法使用
//        mWebView.getSettings().setAppCacheEnabled(false);
//        mWebView.clearCache(true);
//        mWebView.clearHistory();
//        mWebView.clearFormData();
//        //TODO 清楚cookie，效果未知
//        CookieManager.getInstance().removeAllCookie();
//        CookieManager.getInstance().removeSessionCookie();

        mWebView.setWebViewClient(wvc);

        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                top_progress.setCurProgress(newProgress);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                MentorLogger.Log(TAG, "onJsAlert:" + message);
//                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                result.confirm();
                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                MentorLogger.Log(TAG, "onJsConfirm:" + message);
                return super.onJsConfirm(view, url, message, result);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                MentorLogger.Log(TAG, "onJsPrompt:" + url);
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }
        });

        /**文强写的 js回调方法 暂时注释掉 备用
         class JavaScriptObject {
        @JavascriptInterface public void t_buy_apply_bank() {
        StatService.onEvent(mActivity, "t_buy_apply_bank", "[银行卡购买申请]");
        }

        @JavascriptInterface public void t_buy_apply_482002() {
        StatService.onEvent(mActivity, "t_buy_apply_482002", "[现金快线购买申请]");
        }

        @JavascriptInterface public void t_buy_confirm() {
        StatService.onEvent(mActivity, "t_buy_confirm", "[购买确认]");
        }

        @JavascriptInterface public void t_buy_result() {
        StatService.onEvent(mActivity, "t_buy_result", "[购买结果]");
        }

        @JavascriptInterface public void t_redeem_apply_bank() {
        StatService.onEvent(mActivity, "t_redeem_apply_bank", "[取现到银行卡]");
        }

        @JavascriptInterface public void t_redeem_apply_482002() {
        StatService.onEvent(mActivity, "t_redeem_apply_482002", "[取现到现金快线]");
        }

        @JavascriptInterface public void t_redeem_confirm() {
        StatService.onEvent(mActivity, "t_redeem_confirm", "[取现确认]");
        }

        @JavascriptInterface public void t_redeem_result() {
        StatService.onEvent(mActivity, "t_buy_result", "[取现结果]");
        }

        @JavascriptInterface public void t_transfer_apply() {
        StatService.onEvent(mActivity, "t_transfer_apply", "[转换申请]");
        }

        @JavascriptInterface public void t_transfer_confirm() {
        StatService.onEvent(mActivity, "t_transfer_confirm", "[转换确认]");
        }

        @JavascriptInterface public void t_transfer_result() {
        StatService.onEvent(mActivity, "t_transfer_result", "[转换结果]");
        }

        @JavascriptInterface public void zt_t_buy_begin() {
        StatService.onEvent(mActivity, "zt_t_buy_begin", "购买组合");
        }

        @JavascriptInterface public void zt_q_allGroup() {
        StatService.onEvent(mActivity, "zt_q_allGroup", "点击全部组合");
        }

        @JavascriptInterface public void zt_q_group_details() {
        StatService.onEvent(mActivity, "zt_q_group_details", "点击组合进入组合详情");
        }

        @JavascriptInterface public void zt_t_buy_riskHint() {
        StatService.onEvent(mActivity, "zt_t_buy_riskHint", "出现风险提示时");
        }

        @JavascriptInterface public void zt_t_buy_statement() {
        StatService.onEvent(mActivity, "zt_t_buy_statement", "出现投资意愿声明");
        }

        @JavascriptInterface public void zt_t_buy_success() {
        StatService.onEvent(mActivity, "zt_t_buy_success", "购买详情确定按钮");
        }

        @JavascriptInterface public void openBack() {
        isCanPressBack = true;
        }

        @JavascriptInterface public void closeBack() {
        isCanPressBack = false;
        }
        }
         //设置本地调用对象及其接口
         mWebView.addJavascriptInterface(new JavaScriptObject(), "js_invoke");
         **/
        mWebView.loadUrl(url);
    }

    WebViewClient wvc = new WebViewClient() {
        @Override
        public void onLoadResource(WebView view, String url) {
//                MentorLogger.Log(TAG, "onLoadResource url=" + url);
            super.onLoadResource(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView webview, String url) {
            MentorLogger.Log(TAG, "intercept url=" + url);
            if (url.contains("overtime")) {
                loginAfterUrl = webview.getUrl() + "#overtime";
                ActivityUtils.gotoLogin(mActivity, hasUser(), false, findUserId());
                return true;
            }
            onshouldOverrideUrlLoadingCallBack(webview, url);
            return true;
        }

//            @Override
//            public boolean shouldOverrideUrlLoading(WebView webview, String url) {
//                MentorLogger.Log(TAG, "intercept url=" + url);
//                webview.loadUrl(url);
//                return true;
//            }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            MentorLogger.Log(TAG, "onPageStarted");
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            isFinishGo = true;

            String title = view.getTitle();
            MentorLogger.Log("WisdomWebviewTab", "onPageFinished WebView title=" + title);
            if (!isLoadError) {
                mWebView.setVisibility(View.VISIBLE);
                llItemWebError.setVisibility(View.GONE);
                mWebView.loadUrl("javascript:appGetToken('" + getToken() + "')");
            } else {
                isLoadError = false;
                mWebView.setVisibility(View.GONE);
//                    llItemWebError.setVisibility(View.VISIBLE);
                showErrorAlert();
            }

            if ("网页无法打开".equals(title) || title.contains("404")) {
                mWebView.setVisibility(View.GONE);
//                    llItemWebError.setVisibility(View.VISIBLE);
                showErrorAlert();
            }
            onPageFinishedMine(view, url);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            MentorLogger.Log("WisdomWebviewTab", "onReceivedError");
//                mActivity.showToast("onReceivedError");
            isLoadError = true;
            mWebView.setVisibility(View.GONE);
//                llItemWebError.setVisibility(View.VISIBLE);
            showErrorAlert();
            super.onReceivedError(view, request, error);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            MentorLogger.Log("WisdomWebviewTab", "onReceivedHttpError---" + errorResponse.getStatusCode());
//                if ("404".equals(errorResponse.getStatusCode() + "")) {
//                    if (isFinishGo) {
//                        isLoadError = true;
//                    }
//                    mWebView.setVisibility(View.GONE);
//                    llItemWebError.setVisibility(View.VISIBLE);
//                }
            super.onReceivedHttpError(view, request, errorResponse);
        }

        //WebView不能加载https,需要重写这个方法
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }
    };

    public void initUrl(String param) {
        loadUrl = HOST_WEB_URL_HEADER_GYZT + "recommendScheme.html?isFromApp=true&" + param;
        MentorLogger.Log(TAG, "loadUrl=" + loadUrl);
    }

    public void onshouldOverrideUrlLoadingCallBack(WebView webview, String url) {
        MentorLogger.Log(TAG, "url=" + url);

        if (url.startsWith("bmtj:{\"action\":\"")) {
            return;
        }
        if (url.contains("buy.html") || url.contains("buyBack.html")) {
            isCloaseOnBackKey = true;
        } else {
            isCloaseOnBackKey = false;
        }
        if (url.contains("prompt.html")) {
            mIntent.setClass(mActivity, SelectWarmPromptActivity.class);
            mIntent.putExtra("url", url);
            startActivity(mIntent);
        } else if (url.contains("10.0.0.1")) {
            this.finish();
        } else if (url.contains("riskQuestion.html")) {
            startRiskActivity(null);
        } else if (url.contains("overtime")) {
            ActivityUtils.gotoLogin(mActivity, hasUser(), false, findUserId());
        } else if (url.contains(WebViewNetworkProtocol.GOTO_E_CHART)) {
            mIntent.setClass(mActivity, FundDetailEchartActivity.class);
            String param = url.split("\\?")[1];
            param = String.format("%s&cusNo=%s&isFromApp=true", param, getFundCustomerNo());
            mIntent.putExtra("param", param);
            mIntent.putExtra("openType", "GYZT");
            startActivity(mIntent);
        } else {
            webview.loadUrl(url);
        }
    }

    public void onPageFinishedMine(WebView webview, String url) {
//        showToast("url==" + url);
        if (url.contains("overtime")) {
            ActivityUtils.gotoLogin(mActivity, hasUser(), false, findUserId());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
//            mWebView.goBack();// 返回前一个页面
//            return true;
//        }

//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            return true;
//        }
        if (keyCode == KeyEvent.KEYCODE_BACK && isCloaseOnBackKey) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTimeOutCallBack(TimeOutEvent event) {
        if (event.isSuccess) {
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

//        showToast("onResume~~~~~");

//        mWebView.loadUrl("javascript:appGetToken()");
//        mWebView.loadUrl("javascript:appGetToken('" + getToken() + "')");

        if (StringUtils.isNullOrEmpty(loginAfterUrl)) {
            initUrl(HttpUtils.getCommonParams2StringByWeb(mActivity)
                    + "&shareClass=A&cusNo=" + getFundCustomerNo());

            if (CommonUtil.isNetWorkConnected(mActivity)) {
                initView(loadUrl);
            }

        } else {
            mWebView.loadUrl("javascript:appGetToken('" + getToken() + "','" + getFundCustomerNo() + "')");
            loginAfterUrl = loginAfterUrl.replace("#overtime", "");
            mWebView.loadUrl(loginAfterUrl);
            loginAfterUrl = null;
        }
    }

    @OnClick(R.id.tv_item_web_error)
    public void onClick() {
        mWebView.setVisibility(View.GONE);
        llItemWebError.setVisibility(View.GONE);
        initView(loadUrl);
    }

    private IcbcDialog showConfirmAlertDialog;

    private void showErrorAlert() {
        if (showConfirmAlertDialog == null && !mActivity.isFinishing()) {
            showConfirmAlertDialog = new IcbcDialog(mActivity);
            showConfirmAlertDialog.setColor("#FFFFFF");
            showConfirmAlertDialog.setCancelable(false);
            showConfirmAlertDialog.setAnimationEnable(true);
            showConfirmAlertDialog.setTitle("提示");
            showConfirmAlertDialog.setContentText("网页加载失败！");
            showConfirmAlertDialog.setPositiveListener("确定", new IcbcDialog.OnPositiveListener() {
                @Override
                public void onClick(IcbcDialog dialog) {
                    showConfirmAlertDialog.dismiss();
                    showConfirmAlertDialog = null;
                    finish();
                }
            }).show();
        }
    }
}